<div id="ll_users-grid" class="ll_grid"></div>
	<script type="text/javascript">
		
	//setting used variables	
	//----------------------------------
	var ds;
	var sm;
	var cm;
	var grid;
	var add_form;
	var edit_form;
	var LevelDataStore ;

	//----------------------------------
		
	Ext.onReady(function(){	

		//initiate quick tips
		Ext.QuickTips.init();
		
		//-----------------------------------------				
		//display add form window 
		//-----------------------------------------	
		function displayAddFormWindow(){
			if(!add_window.isVisible()){
				add_window.show();
			} else {
				add_form.getForm().reset();
				add_window.toFront();
			}
		}
		//-----------------------------------------				
		//display edit form window
		//-----------------------------------------		
		function displayEditFormWindow(){
			if (grid.selModel.getCount() == 1) {
		    	var selection = grid.selModel.getSelections();
				var selectedId = selection[0].id;
			
				if(!edit_window.isVisible()){
					edit_window.show();
					LevelDataStore.load(); 
					edit_form.getForm().load({
						url:'common/selectTableWhere/' + Math.random(),                          
						waitMsg:'Loading',
						params:{saferequest:true,table:"ll_users",ID:selectedId}
				});	
								
				} else {
					edit_form.getForm().reset();
					edit_window.toFront();
				}
			} else {
				Ext.MessageBox.alert('Warning','Selectati doar o inregistrare pentru editare!');
			} 				
		}		
		//-----------------------------------------				
		//delete action 
		//-----------------------------------------
		
		function ll_users_delete(btn){
		if(btn=='yes'){
		     var selections = grid.selModel.getSelections();
		     var prez = [];
		     for(i = 0; i< grid.selModel.getCount(); i++){
		      	prez.push(selections[i].json.ID);
		     }
		     var encoded_array = Ext.encode(prez);
		     Ext.Ajax.request({  
		        waitMsg: 'Va rugam asteptati',
		        url: 'common/deleteTable/' + Math.random(), 
		        params: { 
		           saferequest:true, table:'ll_users', ids: encoded_array
		          }, 
		        success: function(response){
		          var result=eval(response.responseText);
		          switch(result){
		          case 1:  
		            ds.reload();
		            break;
		          default:
		            Ext.MessageBox.alert('Warning','Nu puteti sterge toate inregistrarile selectate');
		            break;
		          }
		        },
		        failure: function(response){
		          var result=response.responseText;
		          Ext.MessageBox.alert('error','could not connect to the database. retry later');      
		          }
		     });
		  }  
		}
		
		//delete confirmation
		
		function confirmDelete(){
			if(grid.selModel.getCount() == 1){
				Ext.MessageBox.confirm('Confirmation','Sunteti pe cale de a sterge o inregistrare. Continuati?', ll_users_delete);
			} else if(grid.selModel.getCount() > 1){
			  	Ext.MessageBox.confirm('Confirmation','Stergeti inregistrarile selectate?', ll_users_delete);
			} else {
			  	Ext.MessageBox.alert('Warning','Pentru a sterge inregistrari, selectati cel putin o inregistrare!');
			}
		}  		
				

	    // list table
		//-----------------------------------------
	    ds = new Ext.data.Store({
			id: 'table_ds',
			baseParams: {saferequest:true,table:"ll_users"},			
	        proxy: new Ext.data.HttpProxy({
	            url: 'common/getTable/' + Math.random()		//add two segments for quick search [two table fields]
	        }),
	
	        // create reader that reads the table records
	        reader: new Ext.data.JsonReader({
	            root: 'DS_LL_USERS',
	            totalProperty: 'totalCount',
	            id: 'ID',
	            fields: [
	                'user', 'name', 'surname', 'cnp', 'fk_level'
	            ]
	        }),
	
	        // turn on remote sorting
	        remoteSort: true
	    });	

		//set default sort
		ds.setDefaultSort('name', 'desc');
		
		//adding checkbox model - if you want a checkbox selection model
		//sm = new Ext.grid.CheckboxSelectionModel();

		//creating column model
	    cm = new Ext.grid.ColumnModel([/*sm, - uncomment this if you have a checkbox selection model*/
				{header: "Username",		dataIndex: 'user'},
				{header: "Nume",			dataIndex: 'name'},
				{header: "Prenume",			dataIndex: 'surname'},
				{header: "CNP",				dataIndex: 'cnp'},
				{header: "Nivel",			dataIndex: 'fk_level', 	width:50}
		]);
	
	    // by default columns are sortable
	    cm.defaultSortable = true;		
		//creating grid panel
		
	    grid = new Ext.grid.GridPanel({
	        el:'ll_users-grid',				
	        height:469,//586,						
			frame:false,					
	        title:'<?=$title?>',
	        store: ds,
	        cm: cm,
			//sm: sm,					//uncomment this if you have a checkbox selection model
	        trackMouseOver:false,
	        loadMask: true,
	        viewConfig: {
	            forceFit:true
	        },	
			//paging toolbar		
	        bbar: new Ext.PagingToolbar({
	            pageSize: 10,
	            store: ds,
	            displayInfo: true,
	            displayMsg: 'Utilizatori {0} - {1} din {2}',
	            emptyMsg: "No records",
				plugins: new Ext.ux.grid.PageSizer({
				      afterText: '&nbsp;req/page',
					  //beforeText: 'Arata ',
				      sizes: [[5],[10],[25],[50],[100]],
				      comboCfg: {width: 50}
				      })
			}),
	        // inline toolbars
	        tbar:[{
	            text:'Add ',
	            tooltip:'Adaugati',
	            iconCls:'b_add_cls',
				handler:displayAddFormWindow
	        }/*, '-', {					//uncomment this if you have a checkbox selection model
	            text:'Edit',
	            tooltip:'Editati',
	            iconCls:'b_edit_cls',
				handler: displayEditFormWindow
	        }*/,'-',{
	            text:'Delete',
	            tooltip:'Stergeti',
	            iconCls:'b_delete_cls',
				handler:confirmDelete
	        }/*,'-', new Ext.app.SearchField({
					  store: ds,
					  params: {start:0, limit: 23},
					  width: 120
					})*/
			],plugins: new Ext.ux.grid.Search({
						iconCls:'b_search_cls',
						minChars:2,
						autoFocus:true,
						text:'Cauta dupa camp',
						mode:'remote',
						readonlyIndexes:['name'],
						position:'top'
			})					
	    });
		
	    // render it
	    grid.render();
	
	    // trigger the data store load
	    ds.load({params:{start:0, limit:23}});

		grid.on('rowdblclick', function(grid, rowIndex, e) {
		    	var selection = grid.selModel.getSelections();
				var selectedId = selection[0].id;
				displayEditFormWindow();
		});				
		//add form
		//-----------------------------------------
		
		add_form = new Ext.FormPanel({
			id:"add-form",
		    labelAlign: 'top',
		    bodyStyle:'padding:5px',
		    width: 600,        
		    items: [{
		        layout:'column',
		        border:false,
		        items:[{
					defaultType: 'textfield',
		            columnWidth:0.5,
		            layout: 'form',
					border:false,
		            items: 	[{
			                    fieldLabel: 'Nume',
			                    name: 'name',
								allowBlank:false,
								plugins:[Ext.ux.plugins.RemoteValidator],
								rvOptions: {
									url:'common/validateTable/' + Math.random(),
									params:{saferequest:true,table:'ll_users'}
								},								
			                    anchor:'95%'
							},{
								fieldLabel: 'Prenume',
			                    name: 'surname',
								allowBlank:false,
								plugins:[Ext.ux.plugins.RemoteValidator],
								rvOptions: {
									url:'common/validateTable/' + Math.random(),
									params:{saferequest:true,table:'ll_users'}
								},								
			                    anchor:'95%'			
							},{
								fieldLabel: 'CNP',
			                    name: 'cnp',
								allowBlank:false,
								plugins:[Ext.ux.plugins.RemoteValidator],
								rvOptions: {
									url:'common/validateTable/' + Math.random(),
									params:{saferequest:true,table:'ll_users'}
								},									
			                    anchor:'95%'
							}]
		        },{
					defaultType: 'textfield',
		            columnWidth:0.5,
		            layout: 'form',
		            border:false,
		            items: 	[{
								fieldLabel: 'Utilizator[nickname]',
			                    name: 'user',
								allowBlank:false,
								plugins:[Ext.ux.plugins.RemoteValidator],
								rvOptions: {
									url:'common/validateTable/' + Math.random(),
									params:{saferequest:true,table:'ll_users'}
								},										
			                    anchor:'95%'
							},{
			                    fieldLabel: 'Parola',
			                    name: 'pass',
								allowBlank:false,
								plugins:[Ext.ux.plugins.RemoteValidator],
								rvOptions: {
									url:'common/validateTable/' + Math.random(),
									params:{saferequest:true,table:'ll_users'}
								},									
			                    anchor:'95%'
							}, new Ext.form.ComboBox({
								fieldLabel		:'Nivel',
								name			:'fklevel', 
								allowBlank		:false, 
								editable		:false,								
								lazyRender		:true,
								store			:new Ext.data.Store({
												     id: 'fk_level_ds',
													 baseParams: {saferequest:true,code:'lvl'},
												     proxy: new Ext.data.HttpProxy({
												                url: 'common/getReference/' + Math.random()
												     }),
													 reader: new Ext.data.JsonReader({
											            root: 'DS_LVL',
											            id: 'value',
											            fields: ['value', 'option']
											         })
								}),
								hiddenName		:'fk_level',
								displayField	:'option',
								valueField		:'value',									
								triggerAction	:'all',
								emptyText		:'[Selectati Nivelul]'
							})]
		        }]
		    }],
			buttons: [
				{
				  text: 'Save and Close',
				  tooltip:'Salvati si Inchideti',
				  formBind:true,				  
				  handler: function(){
            						add_form.getForm().submit({
								  		url: "common/insertTable/" + Math.random(),
										params:{saferequest:true,table:'ll_users'},
								  		waitTitle: 'Connecting',
								  		waitMsg: 'Validating and saving data...',										
										success:function(form, action, o) {
											if(action.result.code == 0){
												Ext.MessageBox.alert('Atentie:', 'Eroare la adaugare');
												add_form.getForm().reset(); 	
											}else if(action.result.code == 1){
													Ext.MessageBox.alert('Mesaj:', 'Adaugare efectuata cu succes!');
													ds.reload();
													add_form.getForm().reset();
													add_window.hide();
											}
										},										
										failure: function(form, action, o){
						                            if(action.failureType == 'server'){
						                                Ext.Msg.alert('Warning', 'Cannot save to database!', obj.errors.reason);
						                            }else{
						                                Ext.Msg.alert('Warning!', 'Authentication server is unreachable!');
						                            }
												add_form.getForm().reset()	
										}
							  	})
				  			}	
				},{
				  text: 'Cancel',
				  tooltip:'Renuntati',
				  handler: function(){
				  	add_form.getForm().reset();
				    add_window.hide();
				  }
				}
			]
		
		}); //close form and start monitoring for validation	
		add_form.startMonitoring();
		// --------------------------------------
		
		LevelDataStore = new Ext.data.Store({
			  baseParams: {saferequest:true,code:'lvl'},
		      proxy: new Ext.data.HttpProxy({
		        	url: 'common/getReference/' + Math.random(),
		       		method: 'POST'
		    }),
		      reader: new Ext.data.JsonReader({
		          	root: 'DS_LVL',
		          	fields: ['value', 'option']
		    })
		}); 
		
		//edit form
		//-----------------------------------------
		
		edit_form = new Ext.FormPanel({
			id:"edit-form",
		    labelAlign: 'top',
		    bodyStyle:'padding:5px',
		    width: 600,        
		    items: [{
		        layout:'column',
		        border:false,
		        items:[{
					defaultType: 'textfield',
		            columnWidth:0.5,
		            layout: 'form',
					border:false,
		            items: 	[new Ext.form.Hidden({          
							  	fieldLabel: 'ID',  
							  	name: 'ID'
							}),{
			                    fieldLabel: 'Nume',
			                    name: 'name',
								allowBlank:false,
								plugins:[Ext.ux.plugins.RemoteValidator],
								rvOptions: {
									url:'common/validateTable/' + Math.random(),
									params:{saferequest:true,table:'ll_users'}
								},									
			                    anchor:'95%'
							},{
								fieldLabel: 'Prenume',
			                    name: 'surname',
								allowBlank:false,
								plugins:[Ext.ux.plugins.RemoteValidator],
								rvOptions: {
									url:'common/validateTable/' + Math.random(),
									params:{saferequest:true,table:'ll_users'}
								},									
			                    anchor:'95%'			
							},{
								fieldLabel: 'CNP',
			                    name: 'cnp',
								allowBlank:false,
			                    anchor:'95%'
							}]
		        },{
					defaultType: 'textfield',
		            columnWidth:0.5,
		            layout: 'form',
		            border:false,
		            items: 	[{
								fieldLabel: 'Utilizator[nickname]',
			                    name: 'user',
								allowBlank:false,
								plugins:[Ext.ux.plugins.RemoteValidator],
								rvOptions: {
									url:'common/validateTable/' + Math.random(),
									params:{saferequest:true,table:'ll_users'}
								},									
			                    anchor:'95%'
							},{
			                    fieldLabel: 'Parola',
			                    name: 'pass',
								allowBlank:false,
								plugins:[Ext.ux.plugins.RemoteValidator],
								rvOptions: {
									url:'common/validateTable/' + Math.random(),
									params:{saferequest:true,table:'ll_users'}
								},									
			                    anchor:'95%'
							}, new Ext.form.ComboBox({
											fieldLabel		:'Nivel',
											name			:'fklevel',
											lazyRender		:true,
											store			:LevelDataStore,
											hiddenName		:'fk_level',
											displayField	:'option',
											valueField		:'value',
											triggerAction	:'all',
											emptyText		:'[Selectati Nivelul]'
										})
								/*
								 * another way to make selected='selected' on ext form combobox
								 * but this way, leveldatastore loads before form window is called
								 * 
								 *  i use the other way, by calling leveldatastore.load(), after i have a window
								 *  
								 *  
								new Ext.form.ComboBox({
								fieldLabel:	'Nivel',
								id:'fk-level',
								name:'fklevel',
								lazyRender: true,
								store: new Ext.data.Store({
									     autoLoad:true,
										 method:'POST',
									     id: 'fk_level_ds',
									     proxy: new Ext.data.HttpProxy({
										 			disableCaching:false,
									                url: 'common/getReference/lvl/',
													params:{ref_code:"lvl"}
									     }),
										 reader: new Ext.data.JsonReader({
								            root: 'DS_LVL',
								            id: 'value',
								            fields: ['value', 'option']
								         })
								}),
								hiddenName: 	'fk_level',
								displayField: 	'option',
								valueField: 	'value',									
								triggerAction: 	'all',
								emptyText:		'[Selectati Nivelul]'
							})*/
							
							]
		        }]
		    }],
			buttons: [
				{
				  text: 'Save and Close',
				  tooltip:'Salvati si Inchideti',
				  formBind:true,
				  handler: function(){
            						edit_form.getForm().submit({
								  		url: "common/updateTable/" + Math.random(),
										params:{saferequest:true,table:'ll_users'},
								  		waitTitle: 'Connecting..',
								  		waitMsg: 'Validating and saving data...',										
										success:function(form, action, o) {
											if(action.result.code === 0){
												Ext.MessageBox.alert('Atentie:', 'Eroare la actualizare');
												edit_form.getForm().reset(); 	
											}else if(action.result.code == 1){
													Ext.MessageBox.alert('Mesaj:', 'Actualizare efectuata cu succes!');
													ds.reload();
													edit_form.getForm().reset();
													edit_window.hide();
											}
										},										
										failure: function(form, action, o){
						                            if(action.failureType == 'server'){
						                                Ext.Msg.alert('Warning', 'Cannot save to database!', obj.errors.reason);
						                            }else{
						                                Ext.Msg.alert('Warning!', 'Authentication server is unreachable!');
						                            }
												edit_form.getForm().reset()	
										}
							  	})
				  			}
				},{
				  text: 'Cancel',
				  tooltip:'Renuntati',
				  handler: function(){
				  	edit_form.getForm().reset();
				    edit_window.hide();
				  }
				}
			]
		
		}); //close form and start monitoring for validation	
		edit_form.startMonitoring();
		// --------------------------------------
		
		//adding record -> window
		//----------------------------------------

		add_window = new Ext.Window({
		      id: 'add_window',
		      title: 'Adaugare utilizator',
		      closable:false,
		      width: 610,
		      height: 300,
		      plain:true,
		      layout: 'fit',
			  modal:true,
			  closable:true,
			  closeAction:'hide',
			  maximizable:true,
			  items: add_form  
		    });	
			
		//editing record ->window		
		//-----------------------------------------

		edit_window = new Ext.Window({
		      id: 'edit_window',
		      title: 'Editare utilizator',
		      closable:false,
		      width: 610,
		      height: 300,
		      plain:true,
		      layout: 'fit',
		      modal:true,
			  closable:true,
			  closeAction:'hide',
			  maximizable:true,			  
			  items:edit_form
	    });				
	});	
	</script>

